<?php
namespace app\tool;
require_once '../extend/PHPExcel/PHPExcel.php';
class Export
{
    protected $objPHPExcel;

    private static $instance = null;
 
    // 禁止被实例化
    private function __construct()
    {
        $this->objPHPExcel = new \PHPExcel();
    }
 
    // 禁止clone
    private function __clone()
    {
 
    }

    //  实例化自己并保存到$instance中，已实例化则直接调用
    public static function getInstance()
    {
        if (empty(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 下载中奖信息
     * @param array $data
     */
    public function exportDraw($data)
    {
        try {
            $objPHPExcel = $this->objPHPExcel;
            $title = '中奖信息';
            $header = ['A','B','C','D','E'];
            $headerfield = ['用户UUID','奖品','抽奖时间','是否实物','领取信息'];
            $objPHPExcel->setActiveSheetIndex(0);
            $objPHPExcel->getActiveSheet()->setTitle("$title");
            for( $i=0 ; $i <= count($headerfield)-1; $i++){
                $objPHPExcel->getActiveSheet()->setCellValue("$header[$i]".'1',"$headerfield[$i]");
            }
            //设置宽度
            $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(40);
            $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(40);

            foreach($data as $key => $value){
                
                $objPHPExcel->setActiveSheetIndex(0)
                            ->setCellValue('A'.($key+2),$value['uuid'])         //用户UUID
                            ->setCellValue('B'.($key+2),$value['name'])         //奖品
                            ->setCellValue('C'.($key+2),$value['draw_date'])    //抽奖时间
                            ->setCellValue('D'.($key+2),!empty($value['isthing']) && $value['isthing'] == 1 ? '实物' : '虚拟')      //是否实物
                            ->setCellValue('E'.($key+2),$value['draw_info']);   //领取信息
            }
            ob_end_clean();
            header('pragma:public');
            header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$title.'.xlsx"');//octet-stream
            header('Content-Disposition: attachment;filename="'.$title.'.xlsx"');
            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
            $objWriter->save('php://output');
            exit;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }
}